package com.by.yz.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.by.yz.R;

import com.by.yz.activity.base.BaseActivity;
import com.by.yz.adapter.ImageAdapter;
import com.by.yz.common.MFGT;
import com.by.yz.entity.Account;
import com.by.yz.entity.Community;
import com.by.yz.entity.Image;
import com.by.yz.entity.TopicInfo;
import com.by.yz.loginUtil.AccountRESTFul;
import com.by.yz.loginUtil.ImageRESTful;
import com.by.yz.loginUtil.TopicInfoRESTFul;
import com.by.yz.util.IsNetWork;
import com.by.yz.util.ToJSonObject;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * 发表社区健康话题
 * Created by mrs yang on 2016/10/13.
 */
public class ReportTopicActivity extends BaseActivity {
    EditText biaoti_edit;
    EditText content_edit;
    ImageView addimage;
    LinearLayout repor_topic_alyout;
    TopicInfo topic;
    Community community;
    TextView repor_bless;
    EditText bless_cotent;
    private Toast toast = null;

    private ImageAdapter imageAdapter;
    List<String> pathList=new ArrayList<String>();
    private ArrayList<String> path = new ArrayList<>();
    RecyclerView recyclerView;
    public static final int REQUSET_CODE = 100;
    int count =0;//用来判断循环几遍
    Button button;
    boolean inmageFlag = false;
    boolean success;
    private ImageConfig imageConfig;

  //  String imageurlone,imageurltwo,imageurlthree;
    List <String> imgurl=new ArrayList<String>();
    private ProgressDialog dialog;
    int pcount=0;
    IsNetWork isNetWork;
    final int requestCodeCameraStorage = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_report_topic);
        Intent intent=this.getIntent();
        community = (Community) intent.getSerializableExtra("currentCommunity");
        success=intent.getBooleanExtra("reporttopic",false);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (isNetWork.isNetworkAvailable(this)) {
            initView();
            //确定图片的点击事件
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    //上传数据
                    if (pathList.size() == 0) {
                        MaterialDialog nopicture = new MaterialDialog.Builder(ReportTopicActivity.this)
                                .content("您未选择图片")
                                .show();
                    } else {
                        Log.e("zky", "长度是" + pathList.size());
                        dialog = ProgressDialog.show(ReportTopicActivity.this, "正在处理...", getString(R.string.dl_waiting));
                        dialog.show();
                        final BitmapFactory.Options options = new BitmapFactory.Options();
//                      options.inSampleSize =calculateInSampleSize(options, 410, 405);
                        options.inSampleSize = 1;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 0; i < pathList.size(); i++) {
                                    Bitmap img = BitmapFactory.decodeFile(pathList.get(i), options);
                                    String str = bitmapToBase64(img);//将图片进行压缩
                                    if(!img.isRecycled()){
                                        img.recycle();
                                    }
                                    Image image = new Image(str, ToJSonObject.getFileName(pathList.get(i)));
                                    JSONObject topImage = ToJSonObject.beanToJSONObejct(image);
                                    ImageRESTful imageRESTful = new ImageRESTful();
                                    imageRESTful.postImages(topImage, new ImageRESTful.MyPostCallBack() {
                                        @Override
                                        public void ok(JSONObject response) throws JSONException {
                                            Log.e("yanglinjing", "返回储存地址" + response.toString());
                                            String imageUrl = response.getString("link");//图片的解析
                                            Log.e("yanglinjing", "确定二");
                                            String imageurl1 = imageUrl.replace("]", "/");
                                            Log.e("yanglinjing", "确定三");
                                            SaveUrl(imageurl1);
                                            Log.e("yanglinjing", "确定图片");
                                            button.setVisibility(View.GONE);
                                        }

                                        @Override
                                        public void error(String error) {
                                            dialog.dismiss();
                                            inmageFlag = false;
                                        }
                                    });
                                }//for结束
                            }
                        }).start();
                    }

                }
            });
            //发表的点击事件
            repor_topic_alyout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String biaoti = biaoti_edit.getText().toString();
                    String content = content_edit.getText().toString();
                    boolean flag1=true,flag2=true;
                    for(int i=0;i<biaoti.length();i++){
                        String str=biaoti.substring(i,i+1);
                        if(!str.equals(" ")){
                            flag1 = false;
                        }
                    }
                    for(int i=0;i<content.length();i++){
                        String str=content.substring(i,i+1);
                        if(!str.equals(" ")){
                            flag2 = false;
                        }
                    }
                    if (flag1) {
                            Toast.makeText(ReportTopicActivity.this, "标题不能为空", Toast.LENGTH_SHORT).show();
                    }else if(flag2){
                        Toast.makeText(ReportTopicActivity.this, "内容不能为空", Toast.LENGTH_SHORT).show();
                    }else{
                        if(imgurl.size()==0 && pathList.size()!=0){
                            MaterialDialog nopicture = new MaterialDialog.Builder(ReportTopicActivity.this)
                                    .content("您还未确定图片")
                                    .show();
                        }else {
                            ReportTopic();
                        }
                    }
                }
            });
        }else {
            //无网络连接情况
            new AlertDialog.Builder(this)
                    .setTitle("提示!")
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setMessage("检测到您还没开启网络，请开启")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("开启",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    startActivity(new Intent(
                                            Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
                                }
                            }).show();
        }
    }

    private void initView() {
        setToolbarTitle("发表话题");
        imageConfig=new ImageConfig.Builder(new GlideLoader())
                .steepToolBarColor(getResources().getColor(R.color.blue))
                .titleBgColor(getResources().getColor(R.color.blue))
                .titleSubmitTextColor(getResources().getColor(R.color.white))
                .titleTextColor(getResources().getColor(R.color.white))
                // 开启多选   （默认为多选）
                .mutiSelect()
                // 多选时的最大数量   （默认 9 张）
                .mutiSelectMaxSize(3)
                // 已选择的图片路径
                .pathList(path)
                // 拍照后存放的图片路径（默认 /temp/picture） （会自动创建）
                .filePath("/ImageSelector/Pictures")
                // 开启拍照功能 （默认关闭）
                .showCamera()
                .requestCode(REQUSET_CODE)
                .build();

        biaoti_edit = (EditText) findViewById(R.id.biaoti_edit);
        content_edit = (EditText) findViewById(R.id.content_edit);
        repor_topic_alyout = (LinearLayout) findViewById(R.id.report_topic_layout);
        recyclerView=(RecyclerView)findViewById(R.id.topicimage_list);
        button=(Button)findViewById(R.id.button);
        if (community.getCommunityName().contentEquals("祝福墙")) {

            repor_bless = (TextView) findViewById(R.id.report_topic);
            repor_bless.setText("发射您正能量...");
            bless_cotent = (EditText) findViewById(R.id.content_edit);
            bless_cotent.setHint("祝福文字 图片 ...");
        }else if(community.getCommunityName().contentEquals("健康话题")){
            repor_bless = (TextView) findViewById(R.id.report_topic);
            repor_bless.setText("发表健康话题...");
        }
        else if(community.getCommunityName().contentEquals("健康话题")){
            repor_bless = (TextView) findViewById(R.id.report_topic);
            repor_bless.setText("发表健康话题...");
        }
        addimage=(ImageView)findViewById(R.id.addimage);
        addimage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
					int checkStoragePermission = ContextCompat.checkSelfPermission(ReportTopicActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
					int checkCameraPermission = ContextCompat.checkSelfPermission(ReportTopicActivity.this, Manifest.permission.CAMERA);

					if (checkStoragePermission != PackageManager.PERMISSION_GRANTED ||
							checkCameraPermission != PackageManager.PERMISSION_GRANTED){
						ActivityCompat.requestPermissions(ReportTopicActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA},
                                requestCodeCameraStorage);
						return;
					}else{
						path.clear();
						ImageSelector.open(ReportTopicActivity.this, imageConfig);   // 开启图片选择器
					}
				}else{
						path.clear();
						ImageSelector.open(ReportTopicActivity.this, imageConfig);   // 开启图片选择器
				}
            }
        });
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);//设置图片的显示位置
        recyclerView.setLayoutManager(gridLayoutManager);
        imageAdapter = new ImageAdapter(this, path);
        recyclerView.setAdapter(imageAdapter);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
        switch (requestCode){
            case  requestCodeCameraStorage:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
                    path.clear();
                    ImageSelector.open(ReportTopicActivity.this, imageConfig);   // 开启图片选择器
                }else{
                    if(!ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)){
                        new EaseAlertDialog(this, "存储权限被禁止，请开启权限后重试").show();
                    }else if(!ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CAMERA)){
                        new EaseAlertDialog(this, "相机权限被禁止，请开启权限后重试").show();
                    }else{
                        new EaseAlertDialog(this, "相机或存储权限被禁止，请开启权限后重试").show();
                    }
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUSET_CODE && resultCode == RESULT_OK && data != null) {
            pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
            Log.e("lj", pathList.get(0));
            path.clear();
            path.addAll(pathList);
            imageAdapter.notifyDataSetChanged();
        }
    }
    protected  void ReportTopic(){
            AccountRESTFul accountRESTFul = new AccountRESTFul();
            accountRESTFul.get(new AccountRESTFul.IhttpCb() {
                @Override
                public void ok(JSONObject response) {
                    Account account;
                    account = ToJSonObject.jsonToBean(response.toString(), Account.class);
                    Log.e("ylj", account.getLogin().toString());
                    Date date = new Date(System.currentTimeMillis());//获取当前时间
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                    SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");
                    sdf2.setTimeZone(TimeZone.getTimeZone("UTC"));
                    String str = sdf1.format(date) + "T" + sdf2.format(date) + "Z";
                    Log.e("ylj", str);
                    topic = new TopicInfo();
                    String title = biaoti_edit.getText().toString();
                    String content = content_edit.getText().toString();
                    String comunity = community.getCommunityName();
                    String imgStr="";
                    Log.e("ylj","img"+imgurl.toString());
                    for(int i=0;i<imgurl.size();i++)
                    {
                        if(i<imgurl.size()-1)
                        {
                            imgStr+=imgurl.get(i)+",";
                        }
                        else if(i==imgurl.size()-1)
                        {
                            imgStr+=imgurl.get(i);
                        }
                    }
                    topic.setTopicimage(imgStr);
//                topic=new TopicInfo(null,"",str,biaoti_edit.getText().toString(),content_edit.getText().toString(), "",account.getLogin(),str,0 ,0,community.getCommunityName());//复制数据到数据库

                    topic.setId(null);
                    topic.setClicker("");
                    topic.setCreateat(str);
                    topic.setTitle(title);
                    topic.setContent(content);
                    topic.setCreater(account.getLogin());
                    topic.setUpdateat(str);
                    topic.setCount(0);
                    topic.setDisscusscount(0);
                    topic.setComunity(comunity);
                    SubmitTopic();
                }

                @Override
                public void error(String error) {
                    Log.e("ylj", "错误" + error);
                }
            });
    }
    protected  void SubmitTopic(){
        JSONObject jsonObject = ToJSonObject.beanToJSONObejct(topic);
        Log.e("ywx","上传对象"+jsonObject.toString());
        TopicInfoRESTFul topicInfoREST=new TopicInfoRESTFul();
        topicInfoREST.postTopicInfo(jsonObject, new TopicInfoRESTFul.MyPostCallBack() {
            @Override
            public void ok(JSONObject response) throws JSONException {
                Toast.makeText(ReportTopicActivity.this, "话题发表成功", Toast.LENGTH_SHORT).show();
                success=true;
                Log.e("ylj","success"+success);
                Intent intent=new Intent();
                intent.putExtra("reptopic",success);
                ReportTopicActivity.this.finish();
            }
            @Override
            public void error(String error) {
                Log.e("ylj", "错误2" + error);
                Toast.makeText(ReportTopicActivity.this, "字数太多，请控制在255字内", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void SaveUrl(String  url) {
        imgurl.add(count,url);
        Log.e("zky", "获取的地址"+ imgurl.get(count).toString());
        dialog.dismiss();
        count++;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            MFGT.finish(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /*计算图片的缩放值
    *
    * */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height/(float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
            }
        return inSampleSize;
        }
    /*根据路径获得突破并压缩返回bitmap用于显示*/
    public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = calculateInSampleSize(options, 480, 800);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
        }
    /*根据路径删除图片*/
    public static void deleteTempFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }
    public class GlideLoader implements com.yancy.imageselector.ImageLoader {

        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            Glide.with(context)
                    .load(path)
                    .placeholder(com.yancy.imageselector.R.mipmap.imageselector_photo)
                    .centerCrop()
                    .into(imageView);
        }

    }

    //输入框取消键盘事件监听
    @Override
    public boolean dispatchTouchEvent(MotionEvent move) {
        if (move.getAction() == MotionEvent.ACTION_DOWN) {
            View view = getCurrentFocus();
            if (isShouldHideInput(view, move)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(move);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(move)) {
            return true;
        }
        return onTouchEvent(move);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}



